package config

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type MysqlConfig struct {
	Username string
	Password string
	DBName   string
	Host     string
	Port     string
	Charset  string
}

func NewMysqlConfig() *MysqlConfig {
	return &MysqlConfig{
		Username: viper.GetString("mysql.username"),
		Password: viper.GetString("mysql.password"),
		DBName:   viper.GetString("mysql.dbname"),
		Host:     viper.GetString("mysql.host"),
		Port:     viper.GetString("mysql.port"),
		Charset:  viper.GetString("mysql.charset"),
	}
}

func (m *MysqlConfig) ForMatMysql() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local", m.Username, m.Password, m.Host, m.Port, m.DBName, m.Charset)
}

func (m *MysqlConfig) MysqlTestLink() error {
	db, err := gorm.Open(mysql.Open(m.ForMatMysql()), &gorm.Config{})
	if err != nil {
		return err
	}
	sqlDB, err := db.DB()
	defer sqlDB.Close()
	return err
}

func (m *MysqlConfig) LinkMysql(db **gorm.DB, config *gorm.Config) (err error) {
	*db, err = gorm.Open(mysql.Open(m.ForMatMysql()), config)
	if err != nil {
		return
	}
	return nil
}
